import { get, post } from '@/api';
import { ScheduleItem, ScheduleCreateForm } from '@pages/task/schedule/types';

// 获取任务计划列表
export const getScheduleList = async (page: number = 1, pageSize: number = 10) => {
  try {
    const response = await get('/task/schedule/list', {
      params: {
        page: page,
        page_size: pageSize,
      }
    });
    return response.data;
  } catch (error) {
    console.error('获取任务计划失败:', error);
    throw error;
  }
};

// 创建任务计划
export const createSchedule = async (data: ScheduleCreateForm) => {
  try {
    const submitData = {
      ...data,
      interval: data.interval ? data.interval : "{}",
      args: data.args || "[]",
      kwargs: data.kwargs || "{}",
    };
    
    const response = await post('/task/create_schedule', submitData);
    return response.data;
  } catch (error) {
    console.error('创建任务计划失败:', error);
    throw error;
  }
};

// 更新任务计划
export const updateSchedule = async (data: Partial<ScheduleCreateForm> & { id: number }) => {
  try {
    const response = await post('/task/update_schedule', data);
    return response.data;
  } catch (error) {
    console.error('更新任务计划失败:', error);
    throw error;
  }
};

// 删除任务计划
export const deleteSchedule = async (id: number) => {
  try {
    const response = await post('/task/delete_schedule', { id });
    return response.data;
  } catch (error) {
    console.error('删除任务计划失败:', error);
    throw error;
  }
};

// 启动任务
export const startSchedule = async (schedule_id: number, args: string, kwargs: string) => {
  try {
    const response = await post('/task/start', { 
      schedule_id,
      args,
      kwargs
    });
    return response.data;
  } catch (error) {
    console.error('启动任务失败:', error);
    throw error;
  }
};